package com.zzh.takeoutapp.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zzh.takeoutapp.R;
import com.zzh.takeoutapp.activity.ApplyRefundActivity;
import com.zzh.takeoutapp.activity.EvaluateActivity;
import com.zzh.takeoutapp.activity.OrderCarDatelisActivity;
import com.zzh.takeoutapp.activity.PayOrderActivity;
import com.zzh.takeoutapp.activity.SimilarityShopActivity;
import com.zzh.takeoutapp.base.MyBaseAdapter;
import com.zzh.takeoutapp.entity.OrderListBean;
import com.zzh.takeoutapp.event.NetMsgEvent;
import com.zzh.takeoutapp.service.EventbusHelper;
import com.zzh.takeoutapp.service.ServiceUrl;
import com.zzh.takeoutapp.utils.CountTimerUtlis;
import com.zzh.takeoutapp.utils.ImageManager;
import com.zzh.takeoutapp.utils.TimeTools;
import com.zzh.takeoutapp.utils.UtilTool;

import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/7/13.
 */

public class OrderListAdapter extends MyBaseAdapter<OrderListBean, OrderListAdapter.ViewHolder> {
    private OrderListBean orderListBean;
    //用于退出 Activity,避免 Countdown，造成资源浪费。
    private SparseArray<CountDownTimer> countDownMap;

    public OrderListAdapter(List<OrderListBean> list, Context context) {
        super(list, context);
        this.countDownMap = new SparseArray<>();
    }

    /**
     * 清空资源
     */
    public void cancelAllTimers() {
        if (countDownMap == null) {
            return;
        }
        for (int i = 0, length = countDownMap.size(); i < length; i++) {
            CountDownTimer cdt = countDownMap.get(countDownMap.keyAt(i));
            if (cdt != null) {
                cdt.cancel();
            }
        }
    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup container, int type) {
        View view = LayoutInflater.from(container.getContext()).inflate(R.layout.item_list_order, container, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        orderListBean = lists.get(position);
        ImageManager.loadUrlImage(context, orderListBean.getShop_logo(), holder.iv_shop_logo);
        holder.tv_shop_title.setText(orderListBean.getShop_title());
        holder.tv_order_status_label.setText(orderListBean.getOrder_status_label());
        List<OrderListBean.ProductsBean> productsList = orderListBean.getProducts();
        holder.tv_total_price.setText(orderListBean.getProduct_title());
        holder.tv_total_prices.setText("￥" + orderListBean.getTotal_price());
        long timer = orderListBean.getDateline();
        timer = timer - System.currentTimeMillis();
        if (holder.countDownTimer != null) {
            holder.countDownTimer.cancel();
        }
        if (timer > 0) {
            holder.countDownTimer = new CountDownTimer(timer, 1000) {
                public void onTick(long millisUntilFinished) {
                    holder.tv_endtime.setText(TimeTools.getCountTimeByLong(millisUntilFinished));
                }

                public void onFinish() {
                    holder.tv_endtime.setTextColor(context.getResources().getColor(R.color.color_red));
                    holder.tv_endtime.setText(R.string.order_time);
                }
            }.start();
            countDownMap.put(holder.tv_endtime.hashCode(), holder.countDownTimer);
        } else {
            holder.tv_endtime.setTextColor(context.getResources().getColor(R.color.color_red));
            holder.tv_endtime.setText(R.string.order_time);
        }
        LinearLayout.LayoutParams layoutParams =
                new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        holder.layout_shop.setLayoutParams(layoutParams);
        holder.layout_shop.removeAllViews();
        for (int i = 0; i < productsList.size(); i++) {
            View view = View.inflate(context, R.layout.include_item_list_order, null);
            TextView product_name = view.findViewById(R.id.product_name);
            TextView product_number = view.findViewById(R.id.product_number);
            product_name.setText(productsList.get(i).getProduct_name());
            product_number.setText("x" + productsList.get(i).getProduct_number());
            holder.layout_shop.addView(view);
        }
        OrderListBean.ShowBtnBean show_btn = orderListBean.getShow_btn();
        onClick(holder, position);
        setView(holder, show_btn, position);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (lis != null) {
                    lis.onItemClick(view, null, position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        if (lists != null && !lists.isEmpty()) {
            return lists.size();
        }
        return 0;
    }

    private void setView(final ViewHolder holder, OrderListBean.ShowBtnBean show_btn, int position) {
        if (show_btn.getCanel().equals("1")) {//取消订单
            holder.ll_cancel_refund.setVisibility(View.VISIBLE);
        } else {
            holder.ll_cancel_refund.setVisibility(View.GONE);
        }
        if (show_btn.getComment().equals("1")) {//马上评价
            holder.ll_evaluate_refund.setVisibility(View.VISIBLE);
        } else {
            holder.ll_evaluate_refund.setVisibility(View.GONE);
        }
        if (show_btn.getPayback().equals("1")) {//申请退款
            holder.ll_apply_refund.setVisibility(View.VISIBLE);
        } else {
            holder.ll_apply_refund.setVisibility(View.GONE);
        }
        if (show_btn.getAgain().equals("1")) {//再来一单
            holder.ll_recur_refund.setVisibility(View.VISIBLE);
        } else {
            holder.ll_recur_refund.setVisibility(View.GONE);
        }
        if (show_btn.getPay().equals("1")) {//去支付
            holder.ll_pay.setVisibility(View.VISIBLE);
        } else {
            holder.ll_pay.setVisibility(View.GONE);
        }
        if (show_btn.getSee().equals("1")) {//查看评价
            holder.ll_see.setVisibility(View.VISIBLE);
        } else {
            holder.ll_see.setVisibility(View.GONE);
        }
        if (show_btn.getAdmin().equals("1")) {//申请客服
            holder.ll_admin.setVisibility(View.VISIBLE);
        } else {
            holder.ll_admin.setVisibility(View.GONE);
        }
        if (show_btn.getConfirm().equals("1")) {//确认送达
            holder.ll_confirm.setVisibility(View.VISIBLE);
        } else {
            holder.ll_confirm.setVisibility(View.GONE);
        }
        if (show_btn.getCui().equals("1")) {//催单
            holder.ll_cui.setVisibility(View.VISIBLE);
        } else {
            holder.ll_cui.setVisibility(View.GONE);
        }
        if (show_btn.getEndtime().equals("1")) {//倒计时
            holder.ll_endtime.setVisibility(View.VISIBLE);
        } else {
            holder.ll_endtime.setVisibility(View.GONE);
        }
    }

    private void onClick(ViewHolder holder, final int position) {

        holder.ll_cui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (lists.get(position) != null) {
                    NetMsgEvent event = new NetMsgEvent();
                    event.setErrorString(lists.get(position).getOrder_id());
                    event.setMsgType("LL_CUI");
                    EventbusHelper.post(event);
                }
            }
        });
        holder.tv_recur_refund.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent recur_refund = new Intent(context, OrderCarDatelisActivity.class);
                if (lists.get(position) != null) {
                    recur_refund.putExtra("orderListBean", lists.get(position));
                }
                context.startActivity(recur_refund);
            }
        });
        holder.tv_equal_refund.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                context.startActivity(new Intent(context, SimilarityShopActivity.class));
            }
        });
        holder.tv_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent PayOrder = new Intent(context, PayOrderActivity.class);
                if (lists.get(position) != null) {
                    PayOrder.putExtra("orderListBean", lists.get(position));
                }
                context.startActivity(PayOrder);
            }
        });
        holder.tv_cancel_refund.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NetMsgEvent event = new NetMsgEvent();
                event.setErrorString(lists.get(position).getOrder_id());
                event.setMsgType("TV_CANCEL_REFUND");
                EventbusHelper.post(event);
            }
        });
        holder.tv_apply_refund.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                context.startActivity(new Intent(context, ApplyRefundActivity.class));
            }
        });
        holder.tv_evaluate_refund.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, EvaluateActivity.class);
                if (lists.get(position) != null)
                    intent.putExtra("orderListBean", lists.get(position));
                context.startActivity(intent);
            }
        });

    }

    //普通的Holder
    public class ViewHolder extends RecyclerView.ViewHolder {
        public CountDownTimer countDownTimer;
        @Bind(R.id.tv_endtime)
        TextView tv_endtime;
        @Bind(R.id.tv_pay)
        TextView tv_pay;
        @Bind(R.id.tv_see)
        TextView tv_see;
        @Bind(R.id.tv_admin)
        TextView tv_admin;
        @Bind(R.id.tv_confirm)
        TextView tv_confirm;
        @Bind(R.id.tv_cui)
        TextView tv_cui;
        @Bind(R.id.tv_cancel_refund)
        TextView tv_cancel_refund;//取消退款
        @Bind(R.id.tv_apply_refund)
        TextView tv_apply_refund;//申请退款
        @Bind(R.id.tv_evaluate_refund)
        TextView tv_evaluate_refund;//马上评价
        @Bind(R.id.tv_recur_refund)
        TextView tv_recur_refund;//再来一单
        @Bind(R.id.tv_equal_refund)
        TextView tv_equal_refund;//相似商家
        @Bind(R.id.tv_shop_title)
        TextView tv_shop_title;
        @Bind(R.id.tv_order_status_label)
        TextView tv_order_status_label;//支付狀態
        @Bind(R.id.tv_total_price)
        TextView tv_total_price;//总价
        @Bind(R.id.tv_total_prices)
        TextView tv_total_prices;//总价
        @Bind(R.id.layout_shop)
        LinearLayout layout_shop;
        @Bind(R.id.iv_shop_logo)
        ImageView iv_shop_logo;


        @Bind(R.id.ll_cancel_refund)
        LinearLayout ll_cancel_refund;
        @Bind(R.id.ll_apply_refund)
        LinearLayout ll_apply_refund;
        @Bind(R.id.ll_evaluate_refund)
        LinearLayout ll_evaluate_refund;
        @Bind(R.id.ll_recur_refund)
        LinearLayout ll_recur_refund;
        @Bind(R.id.ll_equal_refund)
        LinearLayout ll_equal_refund;
        @Bind(R.id.ll_endtime)
        LinearLayout ll_endtime;
        @Bind(R.id.ll_cui)
        LinearLayout ll_cui;
        @Bind(R.id.ll_confirm)
        LinearLayout ll_confirm;
        @Bind(R.id.ll_admin)
        LinearLayout ll_admin;
        @Bind(R.id.ll_see)
        LinearLayout ll_see;
        @Bind(R.id.ll_pay)
        LinearLayout ll_pay;


        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}